# import sys
# from PyQt6.QtWidgets import QApplication
# from PyQt6 import QtWidgets,QtCore,QtGui
# import cv2
# from PyQt6.QtGui import *
# from PyQt6.QtWidgets import *
# import PyQt6
# from drivingDetect import Ui_driving_detect
# from blinked_detect import BlinkedDetect
# from mp_mouse import MpMouse


# class QmyDetect(QWidget):
#     # 跳转信号
#     switch_window6 = QtCore.pyqtSignal()

#     def __init__(self,parent=None):
#         super().__init__(parent)
#         self.face_driving = Ui_driving_detect()
#         self.face_driving.setupUi(self)
#         self.setGeometry(700, 800, 700, 800)
#         self.center()
#         self.setWindowTitle('比奇堡在逃海绵')
#         self.timer_camera = QtCore.QTimer()
#         self.cap = cv2.VideoCapture()
#         self.CAM_NUM = 0
#         self.slot_driving()
#         self.blinked_detect = BlinkedDetect()
#         self.mp_mouse = MpMouse()
#         self.face_driving.return_2.clicked.connect(self.goDetect_Main)

#     def goDetect_Main(self):
#         self.switch_window6.emit()

#     def paintEvent(self, event):
#         painter = QPainter(self)
#         pixmap = QPixmap("疲劳检测.png")
#         # 绘制窗口背景，平铺到整个窗口，随着窗口改变而改变
#         painter.drawPixmap(self.rect(), pixmap)

#     def slot_driving(self):
#         self.face_driving.beginRec.clicked.connect(self.button_open_camera_click)
#         self.timer_camera.timeout.connect(self.begin_rec)
#         # self.face_driving.return_2.clicked.connect(myChoose.show)

#     '''打开摄像头'''

#     def button_open_camera_click(self):
#         if self.timer_camera.isActive() == False:
#             flag = self.cap.open(self.CAM_NUM)
#             if flag == False:
#                 msg = QtWidgets.QMessageBox.warning(
#                     PyQt6.QtWidgets.QApplication.activeWindow(), u"Warning", u"请检测相机与电脑是否连接正确",
#                     buttons=QtWidgets.QMessageBox.StandardButton.Ok,
#                     defaultButton=QtWidgets.QMessageBox.StandardButton.NoButton)
#             else:
#                 self.timer_camera.start(20)
#         else:
#             self.timer_camera.stop()  # 关闭定时器
#             self.cap.release()  # 释放视频流
#             self.face_driving.cameraPeople.clear()  # 清空视频显示区域

#     '''识别检测画面'''

#     def begin_rec(self):
#         flag, self.rec = self.cap.read()
#         self.blinked_detect.detect(self.rec)
#         self.mp_mouse.detect(self.rec)
#         with open(r'users/behaviors.txt', 'a+', encoding='utf-8') as test:
#             test.seek(0, 0)
#             self.face_driving.prompt.setText(test.read())
#             self.face_driving.prompt.append(test.readline())
#         self.rec = cv2.cvtColor(self.rec, cv2.COLOR_BGR2RGB)
#         # 视频流的长和宽
#         height, width = self.rec.shape[:2]
#         showEnterImage = QtGui.QImage(self.rec.data, width, height, QtGui.QImage.Format.Format_RGB888)
#         ratio = max(width / self.face_driving.cameraPeople.width(), height / self.face_driving.cameraPeople.height())
#         showEnterImage.setDevicePixelRatio(ratio)
#         # 视频流置于label中间部分播放
#         self.face_driving.cameraPeople.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
#         self.face_driving.cameraPeople.setPixmap(QtGui.QPixmap.fromImage(showEnterImage))
#         self.face_driving.cameraPeople.setScaledContents(True)
#         return self.rec

#     '''屏幕居中'''
#     def center(self):
#         qr = self.frameGeometry()  # 得到一个指定主窗口几何形状的矩形
#         cp = self.screen().availableGeometry().center()  # 计算出显示器的分辨率，通过分辨率得出中心点
#         qr.moveCenter(cp)  # 设置为屏幕的中心，矩形大小不变
#         self.move(qr.topLeft())


# if __name__ == '__main__':
#     app = QApplication(sys.argv)
#     app.setWindowIcon(QIcon('logo.ico'))
#     myWidget = QmyDetect()
#     myWidget.show()
#     sys.exit(app.exec())


import sys
from PyQt6.QtWidgets import QApplication
from PyQt6 import QtWidgets, QtCore, QtGui
import cv2
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *
from drivingDetect import Ui_driving_detect
from blinked_detect import BlinkedDetect
from mp_mouse import MpMouse
import numpy as np


class CameraThread(QtCore.QThread):
    change_pixmap_signal = QtCore.pyqtSignal(np.ndarray)

    def __init__(self, blinked_detect, mp_mouse, cam_num=0):
        super().__init__()
        self.blinked_detect = blinked_detect
        self.mp_mouse = mp_mouse
        self.cap = cv2.VideoCapture(cam_num)
        self.running = True

    def run(self):
        while self.running:
            flag, frame = self.cap.read()
            if flag:
                self.blinked_detect.detect(frame)  # 进行眨眼检测
                self.mp_mouse.detect(frame)  # 进行鼠标检测
                self.change_pixmap_signal.emit(frame)

    def stop(self):
        self.running = False
        self.cap.release()


class QmyDetect(QWidget):
    # 跳转信号
    switch_window6 = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.face_driving = Ui_driving_detect()
        self.face_driving.setupUi(self)
        self.setGeometry(700, 800, 700, 800)
        self.center()
        self.setWindowTitle('比奇堡在逃海绵')

        self.blinked_detect = BlinkedDetect()
        self.mp_mouse = MpMouse()

        self.camera_thread = None  # 摄像头线程

        self.face_driving.return_2.clicked.connect(self.goDetect_Main)
        self.face_driving.beginRec.clicked.connect(self.start_camera)

    def goDetect_Main(self):
        self.switch_window6.emit()

    def paintEvent(self, event):
        painter = QPainter(self)
        pixmap = QPixmap("疲劳检测.png")
        painter.drawPixmap(self.rect(), pixmap)

    def start_camera(self):
        if not self.camera_thread:
            # 创建并启动摄像头线程
            self.camera_thread = CameraThread(self.blinked_detect, self.mp_mouse)
            self.camera_thread.change_pixmap_signal.connect(self.update_image)
            self.camera_thread.start()
        else:
            self.camera_thread.stop()
            self.camera_thread = None

    def update_image(self, frame):
        self.rec = frame
        self.save_behavior_info()

        self.rec = cv2.cvtColor(self.rec, cv2.COLOR_BGR2RGB)
        height, width = self.rec.shape[:2]
        showEnterImage = QtGui.QImage(self.rec.data, width, height, QtGui.QImage.Format.Format_RGB888)
        ratio = max(width / self.face_driving.cameraPeople.width(), height / self.face_driving.cameraPeople.height())
        showEnterImage.setDevicePixelRatio(ratio)

        self.face_driving.cameraPeople.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
        self.face_driving.cameraPeople.setPixmap(QtGui.QPixmap.fromImage(showEnterImage))
        self.face_driving.cameraPeople.setScaledContents(True)

    def save_behavior_info(self):
        # 保存行为信息到文本框
        with open(r'users/behaviors.txt', 'a+', encoding='utf-8') as test:
            test.seek(0, 0)
            self.face_driving.prompt.setText(test.read())
            self.face_driving.prompt.append(test.readline())

    def closeEvent(self, event):
        if self.camera_thread:
            self.camera_thread.stop()
        event.accept()

    '''屏幕居中'''
    def center(self):
        qr = self.frameGeometry()
        cp = self.screen().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon('logo.ico'))
    myWidget = QmyDetect()
    myWidget.show()
    sys.exit(app.exec())
